package com.knife.news.manage.action;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import com.knife.news.logic.SiteService;
import com.knife.news.logic.impl.SiteServiceImpl;
import com.knife.news.object.Site;
import com.knife.news.object.Template;
import com.knife.util.CommUtil;
import com.knife.web.Globals;
import com.knife.web.Module;
import com.knife.web.Page;
import com.knife.web.WebForm;

public class TemplateManageAjaxAction extends ManageAction {
	private SiteService siteDAO=SiteServiceImpl.getInstance();

	public Page doInit(WebForm form, Module module) {
		return doChoose(form, module);
	}
	
	public Page doSave(WebForm form, Module module) {
		String pdir = CommUtil.null2String(form.get("sid"));
		String nowdir = CommUtil.null2String(form.get("id"));
		String name = CommUtil.null2String(form.get("name"));
		String saveContent="";
		String templateFile = Globals.APP_BASE_DIR + File.separator + "WEB-INF"
		+ File.separator + "templates" + File.separator + "web" + File.separator;
		if(pdir.length()>0){
			templateFile = templateFile + pdir.replace("_spt_", File.separator) + File.separator;
		}
		if(nowdir.length()>0){
			templateFile = templateFile + nowdir + File.separator;
		}
		String fileContent = CommUtil.null2String(form.get("content"));
		if(fileContent.length()>0){
			saveContent = fileContent;
			saveContent = saveContent.replace("&amp;", "&");
			saveContent = saveContent.replace("&lt;script", "<script");
			saveContent = saveContent.replace("TEXTAREA","textarea");
			saveContent = saveContent.replace("&lt;textarea", "<textarea");
			saveContent = saveContent.replace("&lt;/textarea&gt;", "</textarea>");
		}
		if (name.length() > 0) {
			String path = templateFile + name;
			File tcontent = new File(path);
			try {
				org.apache.commons.io.FileUtils.writeStringToFile(tcontent,saveContent,"UTF-8");
				//fileContent = org.apache.commons.io.FileUtils.readFileToString(tcontent, "UTF-8");
				form.addResult("jvalue", "保存成功");
			} catch (IOException e) {
				form.addResult("jvalue", "保存失败");
				e.printStackTrace();
			}
		}
		//return null;
		return module.findPage("ajax");
	}

	public Page doChoose(WebForm form, Module module) {
		String sid=CommUtil.null2String(form.get("sid"));
		Site site=siteDAO.getSiteById(sid);
		String templateFile = Globals.APP_BASE_DIR + File.separator + "WEB-INF"
				+ File.separator + "templates" + File.separator + "web"
				+ File.separator + site.getTemplate() + File.separator;
		File templatePath = new File(templateFile);
		List<Template> tList = new ArrayList<Template>();
		if (templatePath.exists()) {
			File[] tFiles = templatePath.listFiles();
			Arrays.sort(tFiles, new Comparator<File>(){
				public int compare(File f1, File f2){
					return f1.getName().compareTo(f2.getName());
				}
			});
			for (File afile : tFiles) {
				if (afile.isFile()) {
					Template aTemplate = new Template(afile);
					tList.add(aTemplate);
				}
			}
		}
		form.addResult("tList", tList);
		return module.findPage("dialog");
	}

	public Page doSaveDesign(WebForm form, Module module) {
		String pdir = CommUtil.null2String(form.get("sid"));
		String nowdir = CommUtil.null2String(form.get("id"));
		String name = CommUtil.null2String(form.get("name"));
		int oldIndex = CommUtil.null2Int(form.get("ol"));
		int newIndex = CommUtil.null2Int(form.get("nl"));
		//int oldColumn = CommUtil.null2Int(form.get("oc"));
		int newColumn = CommUtil.null2Int(form.get("nc"));
		String templateFile = Globals.APP_BASE_DIR + File.separator + "WEB-INF"
				+ File.separator + "templates" + File.separator + "web" + File.separator;
		if(pdir.length()>0){
			templateFile = templateFile + pdir.replace("_spt_", File.separator) + File.separator;
		}
		if(nowdir.length()>0){
			templateFile = templateFile + nowdir + File.separator;
		}
		File ft = new File(templateFile + name);
		try {
			String tContent = org.apache.commons.io.FileUtils.readFileToString(ft, "UTF-8");
			Document doc = Jsoup.parse(tContent);
			Element moveCeil = doc.select(".portlet").get(oldIndex);
			doc.select(".portlet").get(oldIndex).remove();
			int j=0;
			for (int i=0;i<doc.select(".column").size();i++) {
				Element el1=doc.select(".column").get(i);
				for (int k=0;k<el1.select(".portlet").size();k++) {
					if (i == newColumn && j == newIndex) {
						//System.out.println("把代码添加到适当的位置：第"+i+"列，第"+k+"行");
						doc.select(".column").get(i).select(".portlet").get(k).before(moveCeil.outerHtml());
					}
					j++;
				}
			}
			//System.out.println("移动的代码:" + moveCeil.html());
			//System.out.println("页面代码:" + doc.html());
			//保存移动后的代码
			tContent = doc.html();
			//处理可视化标记，防止失效
			//tContent = tContent.replace("$!visualDesign", "\n$!visualDesign\n");
			
			//处理Velocity所需格式:所有#parse单独起行
			tContent = tContent.replace("#parse","\n#parse");
			tContent = tContent.replaceAll("#parse[(]&quot;(.*)&quot;[)]","#parse(\"$1\")");
			org.apache.commons.io.FileUtils.writeStringToFile(ft,tContent ,"UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}